package system.dao.page;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: joeytang
 * Date: 2009-2-27
 * Time: 13:52:52
 * 排序条件
 */
public class HibernateSort   implements CriteriaCommand {
    List<Sort> sorts = new ArrayList<Sort>();

    /**
     * 添加排序条件
     * @param property
     * @param order
     */
    public void addSort(String property, String order) {
        sorts.add(new Sort(property, order));
    }

    /**
     * 加载过滤条件
     * @param criteria
     * @return
     */
    public Criteria execute(Criteria criteria) {
        for (Sort sort : sorts) {
            buildCriteria(criteria, sort.getProperty(), sort.getOrder());
        }

        return criteria;
    }

    /**
     * 按规则加�?
     * @param criteria
     * @param property
     * @param order
     */
    private void buildCriteria(Criteria criteria, String property, String order) {
        if (order.equals(Sort.ASC)) {
            criteria.addOrder(Order.asc(property));
        } else if (order.equals(Sort.DESC)) {
            criteria.addOrder(Order.desc(property));
        }
    }

    /***
     * 内部�?
     */
    private static class Sort {
        public final static String ASC = "asc";
        public final static String DESC = "desc";

        private final String property;
        private final String order;

        public Sort(String property, String order) {
            this.property = property;
            this.order = order;
        }

        public String getProperty() {
            return property;
        }

        public String getOrder() {
            return order;
        }
    }
}